<template>
  <div class="body_content">
    <el-cascader :options="userDept" v-model="deptIds" :props="defaultProps" change-on-select style="width: 496px;margin: 20px 0"
      @change="getDept"></el-cascader>
    <Person :availablePersons="availablePersons" :selectedPersons="selectedData" @selectChange="selectChange" />
  </div>
</template>

<script>
  import Person from "./person";
  import {
    departmentManagement
  } from "../../service/service_zbw";
  import {
    diff,
    deepClone
  } from "../../lib/utils";
  import {
    mapState
  } from "vuex";
  export default {
    props: {
      selectedPersons: {
        type: Array
      },
      fatherStatus: {
        type: Boolean
      },
    },
    components: {
      Person
    },
    data() {
      return {
        defaultProps: {
          label: 'deptName',
          value: 'deptId'
        },
        //已选部门的Id
        deptIds: [],
        //可用人员数组
        availablePersons: [],
        //已选中人员Id
        selectedData: [],
        //已选人员完整信息
        selectedDataInfo: [],
        currentId: null
      }
    },
    computed: {
      ...mapState({
        userDept: state => state.userDept
      }),

    },
    methods: {
      /**@function
       * 获取部门Id
       */
      getDept(val) {
        if (val instanceof Array && val.length > 0) {
          let deptId = val[val.length - 1];
          this.getUsers(deptId);
          this.$emit('getDept', deptId);
          this.currentId = deptId;
        }
      },
      /**@function
       * 获取部门下人员
       */
      async getUsers(param) {
        let res = await departmentManagement.getUsers(param);
        if (res.success) {
          this.availablePersons = res.obj;
          this.formatAvailablePersons();
        } else {
          this.availablePersons = [];
        }
      },
      /**
       * 每当人员列表进行切换时
       * 整理可选人员数据
       * 需要将已选中的数据保留在 this.availablePersons 这个可选数组中，这样才能正常显示已选中数据
       * 放入时
       */
      formatAvailablePersons() {
        if (this.selectedDataInfo.length <= 0) {
          console.log('this.availablePersons=========================', this.availablePersons)
          return;
        }
        console.log('this.availablePersons=========================', this.availablePersons)
        console.log('this.selectedDataInfo==================================', this.selectedDataInfo)
        for (let j of this.availablePersons) {
          let sign = true;
          for (let i of this.selectedDataInfo) {
            if (i.userId === j.userId) {
              sign = false;
              break;
            }
          }
          if (sign) {
            i.flag = true;
            this.availablePersons.push(i);
          }
        }
        console.log('this.availablePersons=========================', this.availablePersons)
      },
      /**
       *  从展示页面接收到的已选数据，
       *  格式为 [ { userId: '', userName: '' } ]
       *  需要格式化成userId的纯数组 -> this.selectedData
       */
      formatSelectedData() {
        console.log(this.selectedPersons)
        this.selectedDataInfo = deepClone(this.selectedPersons);
        this.selectedData = [];
        if (this.selectedPersons.length > 0) {
          for (let i of this.selectedPersons) {
            console.log('i------------', i)
            this.selectedData.push(i.userId);
          }
        }
        console.log('this.selectedData==================================', this.selectedData)
        console.log('this.selectedDataInfo==================================', this.selectedDataInfo)
      },
      /**
       * 已选中人员返回
       * 页面显示需要的是 [ { userId: '', userName: '' } ]
       * 按照已选人员Id补全人员信息
       */
      selectChange(val) {
        this.selectedData = val;
        this.selectedDataInfo = [];
        for (let i of this.availablePersons) {
          for (let j of val) {
            if (i.userId === j) {
              this.selectedDataInfo.push(i);
            }
          }
        }
        console.log(this.selectedDataInfo)
        this.deleteOthers();
        this.$emit('selectChange', this.selectedDataInfo);
      },
      /**
       * 删除人员
       * 当人员选中取消时，对应当前的部门Id
       * 若取消的人员Id不是当前的部门Id
       * 则直接移除
       */
      deleteOthers() {
        let arr = [];
        for (let i of this.availablePersons) {
          arr.push(i.userId);
        }
        //查找可用列表和已选列表的差值  差值为未选中人员
        let dif = diff(arr, this.selectedData);
        for (let i of dif) {
          for (let j = 0; j < this.availablePersons.length; j++) {
            //判断未选中人员中是否包含flag字段，如果有，则代表此人员非当前部门人员，直接移除
            if (i === this.availablePersons[j].userId && this.availablePersons[j].flag) {
              this.availablePersons.splice(j, 1);
              break;
            }
          };
        }
      }
    },
    watch: {
      /**@function
       * 根据父级模态框的开关状态去控制操作
       * 如果是true,则为开启   获取可用人员列表，整理已选人员列表
       * 如果是false,则为关闭  清空可用人员列表，清空部门选择的记录
       */
      fatherStatus(newval) {
        if (!newval) {
          this.availablePersons = [];
          this.deptIds = [];
        }
        this.formatSelectedData();
        this.formatAvailablePersons();
        this.availablePersons = [];
      }
    }
  }

</script>

<style scoped>
  .body_content {
    width: 496px;
    margin: 0 auto;
  }

</style>

